package com.ice.app.base.authorization.config;

import java.io.IOException;
import java.util.ArrayList;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import com.ice.app.base.authorization.entity.UserSecurtiyDetails;
import com.ice.app.base.authorization.service.UserSecurityService;
import com.ice.app.system.auth.controller.AuthController;
import com.iceframework.core.entity.User;
import com.iceframework.core.support.security.entity.IJWTInfo;
import com.iceframework.core.support.security.util.JwtUtils;
import com.iceframework.core.utils.JsonUtils;
import com.iceframework.core.utils.WebUtils;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
	
	protected final Log logger = LogFactory.getLog(JwtAuthenticationTokenFilter.class);
	
    @Resource
    private UserDetailsService userDetailsService;
    
    @Resource
    private UserSecurityService userSecurityService;

    @Autowired
	private AuthController authService;

	@Value("${web.jwt.token-header}")
	private String tokenHeader;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    	// 请请求为Method放行
		if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
			chain.doFilter(request, response);
		}
		IJWTInfo user = null;
		try {
			user = getJWTUserName(false,request);
			if (user != null) {
	            logger.info("checking authentication "+user.getUserId());
	            String username = WebUtils.getUserName();
	            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
	            	//获取用户信息
	            	IJWTInfo user2 = WebUtils.getUser();
	            	String userInfoJson = user2.getUserInfo();
	        		User userInfo = JsonUtils.convertString2Obj(userInfoJson, User.class);
	            	UserDetails userDetails = this.getUserSecurityDetails(userInfo);
	            	UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //设置用户登录状态
                    logger.info("authenticated user "+username+", setting security context");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
	            }
	        }
		} catch(Exception e) {
			throw new RuntimeException("get token error："+e.getMessage());
		}
		chain.doFilter(request, response);
    }
    
    /**
	 * 返回session中的用户信息
	 *
	 * @param request
	 * @param ctx
	 * @return
	 */
	private IJWTInfo getJWTUserName(boolean checkToken,HttpServletRequest request) throws Exception {
		String authToken = null;
		authToken = request.getHeader(tokenHeader);
		if (StringUtils.isBlank(authToken)) {
			authToken = request.getParameter(tokenHeader);
			if (StringUtils.isBlank(authToken)) {
				authToken = (String) request.getAttribute(tokenHeader);
				if (StringUtils.isBlank(authToken)) {
					authToken = request.getParameter(tokenHeader);
				}
			}
		}

		// 发送登录日志
		boolean bool = authService.verify(authToken);
		if (bool || !checkToken) {
			return JwtUtils.getJWTInfoByToken(authToken);
		} else {
			return null;
		}
	}
	
	 private UserSecurtiyDetails getUserSecurityDetails(User user) {
			UserSecurtiyDetails userSecurtiyDetails = new UserSecurtiyDetails();
			userSecurtiyDetails.setUserId(user.getUserId());
			userSecurtiyDetails.setUsername(user.getUsername());
		    userSecurtiyDetails.setPassword(user.getPassword());
		    userSecurtiyDetails.setSalt(user.getSalt());
		    userSecurtiyDetails.setEmail(user.getEmail());
		    userSecurtiyDetails.setMobile(user.getMobile());
		    userSecurtiyDetails.setStatus(user.getStatus());
		    userSecurtiyDetails.setOrganId(user.getOrganId());
		    userSecurtiyDetails.setCreateBy(user.getCreateBy());
		    userSecurtiyDetails.setCreateDate(user.getCreateDate());
		    userSecurtiyDetails.setUpdateBy(user.getUpdateBy());
		    userSecurtiyDetails.setUpdateDate(user.getUpdateDate());
		    userSecurtiyDetails.setRemark(user.getRemark());
		    //获取角色信息
		    userSecurtiyDetails.setRoles(new ArrayList<String>());
			return userSecurtiyDetails;
		}
	
}
